<script lang="ts" setup>
import { computed, h, onMounted, ref } from 'vue';
import { NButton, useMessage } from 'naive-ui';
import type { TableColumn } from 'naive-ui/es/data-table/src/interface';
import { useLoading } from '~/packages/hooks';
import { $t } from '@/locales';
import { addConfig, deleteConfig, getConfigTypeList, getConfigurationList, updateConfig } from '@/service/api';
import { toFullModel, toModel } from '@/utils/common';

const message = useMessage();
const { loading, startLoading, endLoading } = useLoading();

const configType = ref<Partial<Api.Basics.SelectItem<number>[]>>([]);

const configList = ref<Api.Configure.Info[]>([]);
const showModal = ref(false);
const modalType = ref<'add' | 'edit'>('add');
const currentItem = ref<Api.Configure.Info | null>(null);

const formRef = ref();
// const formModel = ref<Partial<Api.Configure.Info>>({});
const formModel = ref<Partial<Api.Configure.AddOrEdit>>({
  type: 0
});
const formRules = {
  name: {
    required: true,
    message: $t('page.configure.nameRequired'),
    trigger: 'blur'
  },
  serverUrl: {
    required: true,
    message: $t('page.configure.serverUrlRequired'),
    trigger: 'blur'
  }
  // userName: { required: true, message: $t('page.configure.userNameRequired'), trigger: 'blur' },
  // password: { required: true, message: $t('page.configure.passwordRequired'), trigger: 'blur' }
};

const handleEdit = (item: Api.Configure.Info) => {
  modalType.value = 'edit';
  currentItem.value = { ...item };
  formModel.value = { ...item };
  showModal.value = true;
};

const fetchConfigList = async () => {
  try {
    // 这里应该调用获取配置列表的API
    const { error, data } = await getConfigurationList();
    if (!error) configList.value = data;
  } catch {
    message.error($t('page.configure.fetchFailed'));
  }
};

const handleDelete = async (id: string | undefined) => {
  if (!id) {
    message.error($t('page.configure.informationError'));
    return;
  }
  try {
    // 这里应该调用删除API
    await deleteConfig(id);
    fetchConfigList();
  } catch {
    message.error($t('common.deleteFailed'));
  }
};

const columns = computed<TableColumn<any>[]>(() => [
  { title: $t('page.configure.name'), key: 'name' },
  { title: $t('page.configure.type'), key: 'type' },
  { title: $t('page.configure.userName'), key: 'userName' },
  { title: $t('page.configure.password'), key: 'password' },
  { title: $t('page.configure.serverUrl'), key: 'serverUrl' },
  { title: $t('page.configure.isNormal'), key: 'isNormal' },
  { title: $t('page.configure.token'), key: 'token' },
  {
    title: $t('page.configure.tokenExpireTimeDate'),
    key: 'tokenExpireTimeDate'
  },
  {
    title: $t('common.action'),
    key: 'actions',
    align: 'center',
    render(row: Api.Configure.Info) {
      return h('NSpace', {}, [
        h(NButton, { type: 'primary', size: 'small', onClick: () => handleEdit(row) }, $t('common.edit')),
        h(
          NButton,
          {
            type: 'error',
            class: 'ml-5px',
            size: 'small',
            onClick: () => handleDelete(row.id)
          },
          $t('common.delete')
        )
      ]);
    }
  }
]);

const handleAdd = () => {
  modalType.value = 'add';
  formModel.value = {
    type: 0
  };
  showModal.value = true;
};

/** 批量删除 */
const handleBateDelete = () => {
  // 触发批量删除
};

const handleSubmit = () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      try {
        startLoading();
        const datas = toFullModel(formModel.value);
        if (modalType.value === 'add') {
          // 这里应该调用添加API
          await addConfig(datas);
        } else {
          // 这里应该调用更新API
          if (!currentItem.value!.id) {
            message.error($t('page.configure.informationError'));
            return;
          }
          await updateConfig({
            ...datas,
            id: currentItem.value!.id
          } as Api.Configure.AddOrEdit);
        }
        showModal.value = false;
        fetchConfigList();
      } catch {
        message.error(modalType.value === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess'));
      } finally {
        endLoading();
      }
    }
  });
};

const getList = async () => {
  const { data, error } = await getConfigTypeList();
  if (!error) configType.value = data;
};

onMounted(() => {
  fetchConfigList();
  getList();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!--    <NCard :bordered="false" class="mb-4">-->
    <!--      <NSpace justify="end">-->
    <!--        <NButton type="primary" @click="handleAdd">{{ $t('common.config') }}</NButton>-->
    <!--      </NSpace>-->
    <!--    </NCard>-->

    <NCard :bordered="false">
      <TableHeaderOperation
        v-model:columns="columns as NaiveUI.TableColumnCheck[]"
        :loading="loading"
        @add="handleAdd"
        @delete="handleBateDelete"
        @refresh="fetchConfigList"
      />
      <!--          @delete="handleDelete"-->
      <NDataTable
        :columns="columns"
        :data="configList"
        :pagination="{
          pageSize: 10,
          showSizePicker: true,
          pageSizes: [10, 20, 30, 40],
          showQuickJumper: true
        }"
        :scroll-x="1000"
      />
    </NCard>

    <NModal v-model:show="showModal" :mask-closable="true">
      <NCard
        :bordered="false"
        :title="modalType === 'add' ? $t('common.add') : $t('common.edit')"
        aria-modal="true"
        class="w-600px"
        role="dialog"
        size="huge"
      >
        <NForm
          ref="formRef"
          :model="formModel"
          :rules="formRules"
          :style="{ maxWidth: '640px' }"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
        >
          <NFormItem v-show="false" path="id">
            <NInput v-model:value="formModel.id" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.name')" path="name">
            <NInput v-model:value="formModel.name" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.type')" path="type">
            <NSelect v-model:value="formModel.type" :options="toModel(configType)" size="small" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.serverUrl')" path="serverUrl">
            <NInput v-model:value="formModel.serverUrl" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.userName')" path="userName">
            <NInput v-model:value="formModel.userName" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.password')" path="password">
            <NInput v-model:value="formModel.password" type="password" />
          </NFormItem>
          <NFormItem :label="$t('page.configure.token')" path="token">
            <NInput v-model:value="formModel.token" type="password" />
          </NFormItem>
        </NForm>

        <template #footer>
          <NSpace justify="end">
            <NButton @click="showModal = false">{{ $t('common.cancel') }}</NButton>
            <NButton :loading="loading" type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
          </NSpace>
        </template>
      </NCard>
    </NModal>
  </div>
</template>

<style scoped>
.config-page {
  padding: 16px;
}

@media (max-width: 639px) {
  .config-page {
    padding: 8px;
  }
}
</style>
